package cn.teleware.controller;

import cn.teleware.util.SambaUtil;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author: 洪少尉
 * @Date: 2020/11/13 20:59
 * @Description:
 */
@RestController
public class SendController {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private SambaUtil sambaUtil;

    @PostMapping("send")
    public String send(@RequestParam("multipartFile") MultipartFile file) throws IOException {
        // 文件上传服务上传接口
        String url = "http://localhost:8888/receive";
        // 封装请求参数
        ByteArrayResource resource = new ByteArrayResource(file.getBytes()) {
            @Override
            public String getFilename() {
                return file.getOriginalFilename();
            }

            @Override
            public long contentLength() {
                return file.getSize();
            }
        };
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("multipartFile", resource);
        // 发送请求并输出结果
        System.out.println("--- 开始上传文件 ---");
        String result = restTemplate.postForObject(url, param, String.class);
        System.out.println("--- 访问地址：" + result);
        return result;
    }

    @PostMapping("send2")
    public String send2(@RequestParam("multipartFile") MultipartFile file) throws IOException {
        System.out.println(file);
        sambaUtil.sendBySamba(file);
        sambaUtil.download("上传的.jpg", "C:\\Users\\Administrator\\Desktop\\下载的.jpg");
        return "yes";
    }
}
